import { getAreaListApi, createAreaApi } from '@/api/area'
import { defineStore } from 'pinia'
import { ref, } from 'vue'
import { useCompanyStore } from './company'
import { getMergedAreaListApi } from '../api/area'

export const useAreaStore = defineStore('areaStore', () => {
    const currentArea = ref({})
    const areas = ref([])
    const merged_areas = ref([])

    const setCurrentArea = (company) => {
        currentArea.value = company
    }

    const getAreaNameById = (id) => {
        let area = areas.value.find(item => item.id == id)
        return area?.name || '-'
    }

    const getMergedAreaNameById = (id) => {
        let area = merged_areas.value.find(item => item.id == id)
        return area?.name || '-'
    }

    const fetchAreas = async () => {
        const companyStore = useCompanyStore()
        let companyId = companyStore.currentCompany.id

        let res = await getAreaListApi({
            company_id: companyId,
            offset: 0,
            limit: 500
        })
        areas.value = res.areas
    }

    const fetchMergedAreaList = async (params) => {
        // 获取合并区域数据
        let res = await getMergedAreaListApi(params);
        merged_areas.value = res.data;
    }

    // 新增创建区域的方法
    const createArea = async (areaData) => {
        try {
            const companyStore = useCompanyStore()
            const params = {
                company_id: companyStore.currentCompany.id,
                ...areaData
            }

            const res = await createAreaApi(params)

            // 创建成功后刷新区域列表
            await fetchAreas()

            return res
        } catch (error) {
            console.error('创建区域失败:', error)
            throw error
        }
    }

    return {
        areas,
        currentArea,
        merged_areas,
        setCurrentArea,
        fetchAreas,
        getAreaNameById,
        fetchMergedAreaList,
        getMergedAreaNameById,
        createArea  // 导出新增的方法
    }
}, {
    persist: true
})